package com.huaxin.thirdpartyinterface.wechat;

import com.alibaba.fastjson.JSONObject;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Component
public class WeChatUtils {

    //微信appid
    @Value("${wechat.smallProgram.appId}")
    private String appId;
    @Value("${wechat.smallProgram.appSecret}")
    private String appSecret;

    /**
     * 解密微信小程序的加密数据
     *
     * @param encryptedData 加密数据
     * @param sessionKey    会话密钥
     * @param iv            初始向量
     * @return 解密后的 JSON 数据
     */
    public JSONObject decryptData(String encryptedData, String sessionKey, String iv) throws Exception {
        byte[] data = Base64.decode(encryptedData);
        byte[] key = Base64.decode(sessionKey);
        byte[] initVector = Base64.decode(iv);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector);

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] result = cipher.doFinal(data);

        // 处理解密后的数据，去掉填充
        int pad = result[result.length - 1];
        if (pad < 1 || pad > 32) {
            pad = 0;
        }
        String decrypted = new String(result, 0, result.length - pad, "UTF-8");

        return JSONObject.parseObject(decrypted);
    }

    /**
     * 使用 code 换取 session_key 和 openid
     *
     * @param code 小程序前端获取的临时登录凭证
     * @return 包含 session_key 和 openid 的 JSON 对象
     */
    public JSONObject getSessionKeyAndOpenId(String code) {
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        return JSONObject.parseObject(response.getBody());
    }
}